<?php
/**
 * 难度 简单
 * 题目链接 https://leetcode.cn/problems/number-of-segments-in-a-string/description/
 */

class Solution {

    /**
     * @param String $s
     * @return int
     */
    public static function countSegments(string $s): int
    {
        // 我的判断逻辑是 遇到空格才会记数单词数量 所以我要加一个空格
        $s .= ' ';
        $单词 = '';
        $单词数量 = 0;
        for ($i=0; $i < strlen($s); $i++) { 
            if ($s[$i] == ' ' && $单词 != '') {
                $单词数量++;
                $单词 = '';
            } elseif ($s[$i] != ' ') {
                $单词 .= $s[$i];
            }
            // echo "单词=$单词 单词数量=$单词数量\n";
        }

        return $单词数量;
    }
}

$test = [
    ["Hello, my name is John"],
    ["Hello"],
    [""],
    [", , , ,        a, eaefa"],
];
$result = [
    5,
    1,
    0,
    6,
];

foreach ($test as $key => $value) {
    $r = Solution::countSegments($value[0]);
    if ($r !== $result[$key]) {
        echo sprintf("第%d个case不通过 期望=%s 结果=%s\n", 
            $key+1, 
            $result[$key],
            $r
        );
    }
}